package com.school.chapter01.DoubleLinkedList_;

public class Doubly {
    public static void main(String[] args) {
        Node[] node = new Node[3] ;
        node[0] = new Node(2);
        node[1] = new Node(3);
        node[2] = new Node(4);
        Doubly doubly = new Doubly();
        doubly.insert(node[0]);
        doubly.insert(node[1]);
        doubly.insert(node[2]);
        doubly.print();

    }

    public Node first;
    public Node last;

    public boolean isEmpty() {
        return first == last;
    }

    public void print() {
        Node current = first;
        while (current != null) {
            System.out.println("[" + current.data + "]");
            current = current.rnext;
        }
        System.out.println();
    }

    public void insert(Node newN) {
        Node tmp;
        Node newNode;
        if (this.isEmpty()) {
            first = newN;
            first.rnext = last;
            last = newN;
            last.lnext = newN;
        } else {
            if (newN.lnext == null) { //插入到表头
                first.lnext = newN;
                newN.rnext = first;
                first = newN;
            } else {
                if (newN.rnext == null){ //插入到表尾
                    last.rnext = newN;
                    newN.lnext = last;
                    last = newN;
                }else{ //插入中间位置
                    newNode = first;
                    tmp = first;
                    while (newN.rnext != newNode.rnext){
                        tmp = newNode;
                        newNode = newNode.rnext;
                    }
                    tmp.rnext = newN;
                    newN.rnext = newNode;
                    newNode.lnext = newN;
                    newN.lnext = tmp;
                }
            }
        }
    }

    //删除节点
    public void delete(Node delNode){
        Node newNode;
        Node tmp;
        if (first == null){
            System.out.println("[链表是空的]");
            return;
        }
        if (delNode == null){
            System.out.println("[错误：del不是链表中的节点]");
            return;
        }
        if (first.data == delNode.data) { //要删除的节点再链表头部
            first = first.rnext;
            first.lnext = null;
        }else if(last.data == delNode.data){ //要删除的节点在链表尾部
            newNode = first;
            while(newNode.rnext != last)
                newNode = newNode.rnext;
            newNode.rnext = null;
            last = newNode;
        }
        else{
            newNode = first;
            tmp = first;
            while (newNode.data != delNode.data){
                tmp = newNode;
                newNode = newNode.rnext;
            }
            tmp.rnext = delNode.rnext;
            tmp.lnext = delNode.lnext;
        }
    }

}

class Node {
    int data;
    Node rnext;
    Node lnext;

    public Node(int date) {
        this.data = date;
        this.rnext = null;
        this.lnext = null;
    }
}
